/*
 * Copyright 2009 Prime Technology.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package br.jm.financeiro.view;

import br.jm.financeiro.entity.Usuario;
import br.jm.financeiro.sistema.eao.UsuarioEao;
import java.io.Serializable;
import java.util.Map;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

public class GuestPreferences implements Serializable {

    private static final long serialVersionUID = 1L;
    private String theme = "aristo"; //default
    private FacesContext ctx;
    private HttpSession session;
    private UsuarioEao usuarioEAO;

    public String getTheme() {
        ctx = FacesContext.getCurrentInstance();
        session = (HttpSession) ctx.getExternalContext().getSession(false);

        Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();

        try {
            Usuario user = (Usuario) session.getAttribute("usuarioAutenticado");

            if (user != null) {
                theme = user.getDscThema();
            }
        } catch (Exception e) {
            e.getMessage();
        }

        if (params.containsKey("theme")) {
            theme = params.get("theme");
        }

        return theme;
    }

    public void setTheme(String theme) {
        try {
            ctx = FacesContext.getCurrentInstance();
            session = (HttpSession) ctx.getExternalContext().getSession(false);

            usuarioEAO = UsuarioEao.getInstance();

            Usuario user = (Usuario) session.getAttribute("usuarioAutenticado");
            user.setDscThema(theme);
            session.setAttribute("usuarioAutenticado", user);
            usuarioEAO.edit(user);
        } catch (Exception e) {
            e.getMessage();
        }
        if (theme == null) {
            theme = "aristo";
        }
        this.theme = theme;
    }
}
